package com.none.web.service.logs.impl;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.none.core.common.utils.CreateID;
import com.none.core.common.utils.StringUtil;
import com.none.core.exception.ValidateException;
import com.none.core.service.BaseServiceSupport;
import com.none.web.model.TLogs;
import com.none.web.service.logs.ILogsService;

/**
 * 
 * @Description: 日志管理Service实现
 * @author Bing
 * @date 2015年6月25日 上午10:28:53
 */
@Service("logService")
public class LogsServiceImpl extends BaseServiceSupport implements ILogsService {
	@Autowired
    JdbcTemplate jdbcTemplate;

	@Override
	public TLogs saveLogs(TLogs logs, String type, String userId)
			throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("user.userUnExist");
		
		if(logs==null){
			throw new ValidateException("news.unExist");
		}
		logs.setId(CreateID.getID());
		logs.setDate_time(new Timestamp(new Date().getTime()));
		logs.setType(type);
		logs.setUser_id(userId);
		logs.setRemark("");
		// 保存
		if (saveEntity(logs) == null) {
			throw new ValidateException("common.illegalRequest");
		} else {
			return logs;
		}
	}

	@Override
	public Integer getBrowseTimes(String contentId, String type, String userId)
			throws Exception {
		Integer times = 0;
		String sql ="";
		if("".equals(type)){
			 sql = "select t.browse_times from t_browse_times t where  t.contentId='"+contentId+"'";
		}else{
			 sql = "select t.browse_times from t_browse_times t where t.type='"+type+"' and t.contentId='"+contentId+"'";
		}
		List<Map<String, Object>> listMap=this.jdbcTemplate.queryForList(sql);
		if(listMap!=null && listMap.size()>0){
			times=Integer.parseInt(StringUtil.toStringNumber(listMap.get(0).get("browse_times")));
		}
		return times;
	}

	@Override
	public Integer getAllBrowseTimes(String contentId, String type,
			String userId) throws Exception {
		Integer times = 0;
		String sql ="";
		if("".equals(type)){
			 sql = "select count(*) num from t_logs t where t.contentId='"+contentId+"'";
		}else{
			 sql = "select count(*) num from t_logs t where t.type='"+type+"' and t.contentId='"+contentId+"'";
		}
		List<Map<String, Object>> listMap=this.jdbcTemplate.queryForList(sql);
		if(listMap!=null && listMap.size()>0){
			times=Integer.parseInt(StringUtil.toStringNumber(listMap.get(0).get("num")));
		}
		return times;
	}
	
}
